package org.apache.http.examples.entity.mime;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.EntityBuilder;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * Example how to use multipart/form encoded POST request.
 */
public class Test {

	public static void main(String[] args) throws Exception {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		try {
			HttpPost httppost = new HttpPost("http://localhost:8080" + "/mchappweb/dao/save");

			// FileBody bin = new FileBody(new File(args[0]));
			// StringBody comment = new StringBody("A binary file of some kind",
			// ContentType.TEXT_PLAIN);
			EntityBuilder eb = EntityBuilder.create();
			eb.setContentType(ContentType.APPLICATION_JSON);
			eb.setContentEncoding("utf8");
			eb.setText("{\"b\":\"是中\"}");
			HttpEntity reqEntity =eb.build();
//[Content-Type: text/plain; charset=ISO-8859-1,Content-Length: 9,Chunked: false]
			// HttpEntity reqEntity =
			// MultipartEntityBuilder.create().addPart("bin",
			// bin).addPart("comment", comment).build();

			httppost.setEntity(reqEntity);

			System.out.println("executing request " + httppost.getRequestLine());
			CloseableHttpResponse response = httpclient.execute(httppost);

			try {
				System.out.println("----------------------------------------");
				System.out.println(response.getStatusLine());
				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					System.out.println("Response content length: " + resEntity.getContentLength());
					System.out.println(resEntity.toString());
					System.out.println(IOUtils.toString(resEntity.getContent()));
				}
				EntityUtils.consume(resEntity);
			} finally {
				response.close();
			}
		} finally {
			httpclient.close();
		}
	}

}
